# -*- coding: utf-8 -*- 
# @Time : 2020-12-07 22:25 
# @Author : derek.zhang 
# @File : views.py 
# @Software: PyCharm
import platform

import django
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.http import require_http_methods
from django.views.generic import TemplateView

from appinput.models import App
from deploy.models import DeployPool
from manabe.forms import RegisterForm, LoginForm

# 此装饰器限制 请求此视图的request 只能是 GET  和 POST 方法
from serverinput.models import Server


@require_http_methods(['GET','POST'])
def user_register(request):
    error = []
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            username = data['username']
            email = data['email']
            password = data['password']
            password2 = data['password2']
            if not User.objects.all().filter(username__iexact=username):
                if form.pwd_vaildate(password,password2):
                    user = User.objects.create_user(username= username, password=password, email=email)
                    user.save()
                    user = authenticate(username=username,password=password)
                    login(request, user)
                    return redirect_login(request)









                else:
                    error.append('密码不一致，请确认')
        else:
            error.append('请确认各个输入框无误')
        return render(request, 'account/register.html', locals())
    else:
        print("11111")
        form = RegisterForm()
        return render(request, 'account/register.html', locals())

@require_http_methods(['GET','POST'])
def user_login(request):
    error = []
    if request.method == 'POST':
        form = LoginForm(request.POST)
        # 验证码处理逻辑
        vc = request.POST['vc']
        if vc.upper() != request.session['verify_code']:
            error.append('验证码错误!')
            return render(request, 'account/login.html', locals())
        if form.is_valid():
            data = form.cleaned_data
            username = data['username']
            password = data['password']
            user = authenticate(username=username, password=password)
            if user and user.is_active:
                login(request, user)
                return redirect_login(request)

            else:
                error.append('请输入正确的用户名和密码')
                return render(request, 'account/login.html', locals())
        else:
            return render(request, 'account/login.html', locals())
    else:
        form = LoginForm()
        return render(request, 'account/login.html', locals())


class IndexView(TemplateView):
    template_name = 'manabe/index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['current_page'] = "index"
        context['app_count'] = App.objects.count()
        context['server_count'] = Server.objects.count()
        context['deploy_count'] = DeployPool.objects.count()
        # 以下部分是用于从用户浏览器中获取IP地址，浏览器版本和语言 ， 注意其用法
        context['REMOTE_ADDR'] = self.request.META.get("REMOTE_ADDR")
        context['HTTP_USER_AGENT'] = self.request.META.get("HTTP_USER_AGENT")
        context['HTTP_ACCEPT_LANGUAGE'] = self.request.META.get("HTTP_ACCEPT_LANGUAGE")

        # 获取操作系统，Python 版本，Django 版本
        context['platform'] = platform.platform()
        context['python_version'] = platform.python_version()
        context['django_version'] = django.get_version()

        return context

# 注意用法
def redirect_login(request):
    login_url = reverse('index')
    return HttpResponseRedirect(request.POST.get('next', login_url) or login_url)
